package com.mz.mattress.client.plan.impl;

import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.*;
import com.mz.mattress.api.enums.OrderStatusEnum;
import com.mz.mattress.api.enums.OrderTagEnum;
import com.mz.mattress.api.enums.TaskStatusEnum;
import com.mz.mattress.api.redis.RedisKeys;
import com.mz.mattress.api.util.IdUtil;
import com.mz.mattress.client.api.req.UseOrderReq;
import com.mz.mattress.client.mapper.*;
import com.mz.mattress.client.plan.AbstractPlanExecutor;
import com.mz.mattress.client.service.OrderService;
import com.mz.mattress.client.task.TaskStep;
import com.mz.mattress.client.util.GenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

//任务步骤处理器

/**
 * 新注册会员， 下订单 ，核销订单
 * 老会员 ，已有订单，直接核销
 * 老会员，下订单，核销
 * @param
 */
@Slf4j
@Service("createOrderExecutor")
public class CreateOrderExecutor extends AbstractPlanExecutor {

    public static final String LOG_START = "create_order_{}_taskId={}";

    public static final Integer goodsId = 2;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public CreateOrderExecutor(PlanTaskDataMapper planTaskDataMapper) {
        super(planTaskDataMapper);
    }

    @TaskStep(value = 0, delayTime = 10)
    public void register(PlanTaskData data) {

        log.info(LOG_START, "register", data.getId());

        data.setStatus(TaskStatusEnum.RUNNING.getValue());

        Object obj = redisTemplate.boundListOps(RedisKeys.CREATE_ORDER_QUEUE).leftPop();
        if (obj == null) {
            log.warn(LOG_START, "create_order_queue_is_null", data.getId());
            data.setStatus(TaskStatusEnum.FAILED.getValue());
            return;
        }

        Integer goodsId = (Integer) obj;
        data.setGoodsId(goodsId);

        if (data.getGoodsId() == 2) {
            //注册新用户  单次卡
            Long memberId = IdUtil.getMemberId();

            Member member = new Member();
            member.setId(memberId);
            member.setMobile(GenUtil.generateMobileNumber());
            member.setAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
            member.setNickname("微信用户");
            member.setStatus(0);
            member.setCount(0);
            memberMapper.insert(member);

            data.setMobile(member.getMobile());
            data.setMemberId(member.getId());
        } else {

            Object object = redisTemplate.boundListOps(RedisKeys.OLD_MOBILE_QUEUE).rightPop();
            if (object == null) {
                log.warn(LOG_START, "register_no_mobile", data.getId());
                return;
            }

            data.setMobile((String) object);

            Member member = memberMapper.selectByMobile(data.getMobile());
            if (member == null) {
                log.warn(LOG_START, "member_is_null_mobile=" + data.getMobile(), data.getId());
            }

            data.setMemberId(member.getId());
        }

    }

    @TaskStep(value = 1, delayTime = 30)
    public void createOrder(PlanTaskData data) {

        log.info(LOG_START, "createOrder", data.getId());

        Goods goods = goodsMapper.selectById(data.getGoodsId());
        if (goods == null) {
            data.setStatus(TaskStatusEnum.FAILED.getValue());
            return;
        }

        Integer money = 0;
        Integer couponMoney = 0;
        if (data.getGoodsId() == 2) {
            money = 990;
            couponMoney = 8910;
        } else {
            money = goods.getPrice();
        }

        Long orderId = IdUtil.generatedCommonId(OrderTagEnum.mattressOrder);
        Order order = new Order();
        order.setOrderId(orderId);
        order.setTotalMoney(goods.getPrice());
        order.setMemberId(data.getMemberId());
        order.setMobile(data.getMobile());
        order.setCouponMoney(couponMoney);
        if (couponMoney > 0) {
            order.setCouponId(1391);
        }
        order.setMoney(money);
        order.setPayMoney(money);
        order.setGoodsId(goods.getId());
        order.setTitle(goods.getTitle());
        order.setCount(goods.getCount());
        order.setRemain(goods.getCount());
        order.setStatus(OrderStatusEnum.PAID.getValue());
        orderMapper.insert(order);

        data.setOrderId(orderId);
    }

    @TaskStep(value = 2, delayTime = 12)
    public void bindDevice(PlanTaskData data) {

        log.info(LOG_START, "bindDevice", data.getId());

        Object object = redisTemplate.boundListOps(RedisKeys.PLAN_DEVICE_QUEUE).rightPop();
        if (object == null) {
            log.error("device_queue_is_empty");
            data.setStatus(TaskStatusEnum.FAILED.getValue());
            return;
        }

        String deviceCode = object.toString();

        UseOrderReq req = new UseOrderReq();
        req.setOrderId(data.getOrderId());
        req.setDeviceCode(deviceCode);
        req.setMemberId(data.getMemberId());
        req.setDev(2);

        Result<Integer> result = orderService.bindDevice(req);

        data.setStatus(TaskStatusEnum.SUCCESS.getValue());
        data.setDeviceCode(deviceCode);

        Device device = deviceMapper.selectByDeviceCode(deviceCode);
        if (device != null) {
            data.setMerchantId(device.getMerchantId());
        }

    }


}
